package com.financing.wap.web.controller.api;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.DstFileRecordDTO;
import com.financing.wap.service.IDstFileRecordService;
import com.financing.wap.util.AliyunOssUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

@Controller("fileUploadController")
@RequestMapping("/api")
public class FileUploadController  extends BaseController{

	private String fileBaseDir=PropertiesUtils.getValue("fileBaseDir");
	
	private Map<String,String> fileDir = new HashMap<String,String>();
	
	private List<String> allowList;
	@Autowired
	private IDstFileRecordService dstFileRecordService;//文件记录服务
	
	private String fileTypeDir=PropertiesUtils.getValue("fileTypeDir");
	
	private String fileAllowTypes=PropertiesUtils.getValue("fileAllowTypes");

	private String aliyunOss=PropertiesUtils.getValue("AliyunOss");
	
	Logger logger = Logger.getLogger(getClass());

	@RequestMapping("/fileUpload")
	public ResultMap fileUpload(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		String filePath = getFilePath(request);
		if(StringUtil.isNullOrEmptyStr(filePath)){
			log.warn("file type not exist!");
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SAVE_FILE_DIR_ERROR);
			getJsonData(request,response,result);
			return null;
		}
		
		try{
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			if(multipartResolver.isMultipart(request))
	        {
	            //将request变成多部分request
	            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
	           //获取multiRequest 中所有的文件名
	            Map<String,MultipartFile> mutipartFileMap = multiRequest.getFileMap();
	             
	            Iterator<Entry<String, MultipartFile>> mutipartFileIterator =  mutipartFileMap.entrySet().iterator();
	            while(mutipartFileIterator.hasNext())
	            {
	            	Entry<String, MultipartFile> entry = mutipartFileIterator.next();
	                MultipartFile file=entry.getValue();
	                if(!isAllowFileType(file.getContentType())){
	                	log.error("upload file type error!");
	                	result.setStatus(STATUS.ERROR);
	        			result.setStatusCode(ResultMap.STATUS_CODE_FILE_TYPE_ERROR);
	        			getJsonData(request,response,result);
	        			return null;
	                }
	                if(file!=null && (!file.isEmpty()) &&  entry.getKey() !=null && entry.getKey().length()>0)
	                {
						//文件类型
						String fileType = request.getParameter("fileType");

						//文件名称
						String  originalFilename = file.getOriginalFilename();

						//目录
						StringBuffer fileFull = new StringBuffer();
						fileFull.append(filePath)
								.append("/")
								.append(StringUtil.dateNowStr("yyyyMMdd"));
						//文件全路径
						StringBuffer fileFullPath = new StringBuffer(fileFull.toString());

						//名称
						String randomName = fileType+"_"+System.currentTimeMillis()+"";

						//后缀
						String houzhui = originalFilename.substring(originalFilename.lastIndexOf("."));
						fileFullPath.append("/")
								.append(randomName)
								.append(houzhui);
						//判断 是否-oss
						logger.info("fileUpload.shtml  AliyunOss:"+aliyunOss);
						if(!"true".equals(aliyunOss)) {
							//目录
							File dir = new File(fileBaseDir + fileFull.toString());
							if (!dir.exists()) {
								dir.mkdirs();
							}
							//上传 文件
							File fileTmp = new File(fileBaseDir + fileFullPath.toString());
							if (!fileTmp.exists()) {
								fileTmp.createNewFile();
								logger.info("create new file !");
							}
							file.transferTo(fileTmp);
						}else{
							AliyunOssUtil.writeFile(file.getInputStream(), fileFullPath.toString().substring(1,fileFullPath.toString().length()));
						}
						
						String logicFullpath = fileFullPath.toString();
						//如果是oss走绝对路径
						if("true".equals(aliyunOss)){
							logicFullpath=CommonConstantUtil.OSS_PATH+logicFullpath;
						}
						
						//添加- 文件记录
						String refid = ServletRequestUtils.getStringParameter(request, "refid");
						DstFileRecordDTO fileRecord = new DstFileRecordDTO();
						fileRecord.setType(fileType);
						fileRecord.setRefid(refid);
						fileRecord.setFileSuffix(houzhui);
						fileRecord.setFileName(originalFilename);
						fileRecord.setLogicName(randomName+houzhui);
						
						fileRecord.setLogicFullpath(logicFullpath);
						dstFileRecordService.insert(fileRecord);
						
	        			result.setStatus(STATUS.SUCCESS);
	        			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
						result.setAttribute("fileType", file.getContentType());
						result.setAttribute("fName", originalFilename);
						result.setAttribute("fileUrl", logicFullpath);
						result.setAttribute("fileid", fileRecord.getId());
						
	        			getJsonData(request,response,result);
	        			return null;
	                }
	                 
	            }
	           
	        }
		}catch(Exception e){
			log.error("upload file error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.RESULT_CODE_SYSTEM_ERROR);
			getJsonData(request,response,result);
			return null;
		}
		
		log.warn("no file upload!");
		result.setStatus(STATUS.ERROR);
		result.setStatusCode(ResultMap.STATUS_CODE_NO_FILE_UPLOAD);
		
		getJsonData(request,response,result);
		
		return null;
		
		
		
	}

	@Autowired
	private void setDir(){
		String[] fileTypes = fileTypeDir.split(";");
		for(String tmp : fileTypes){
			String[] tmpTypes = tmp.split(":");
			if(tmpTypes.length==2){
				fileDir.put(tmpTypes[0], tmpTypes[1]);
			}
		}
		
		//注入允许上传的文件类型
		allowList = new ArrayList<String>();
		String[] allowTypes = fileAllowTypes.split(",");
		for(String type : allowTypes){
			allowList.add(type);
		}
		
	}
	
	/**
	 * 
	 * @Title: getFilePath
	 * @Description: 根据文件类型选择上传文件路径 
	 * @param @param request
	 * @param @return   
	 * @return String   
	 * @throws
	 */
	private String getFilePath(HttpServletRequest request){
		String fileType = request.getParameter("fileType");
		if(StringUtil.isNullOrEmptyStr(fileType)){
			fileType = "common";
		}
		return fileDir.get(fileType);
	}
	/**
	 * 
	 * @Title: isAllowFileType
	 * @Description: 判断文件类型是否未允许的类型 
	 * @param @param type
	 * @param @return   
	 * @return boolean   
	 * @throws
	 */
	private boolean isAllowFileType(String type){
		return allowList.contains(type.toLowerCase());
	}
	private void getJsonData(HttpServletRequest request,HttpServletResponse response,Object result)
    {
        String callback = null;

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;

        if(result == null)
        {
            try
            {
                String jsonStr = "";
                out = response.getWriter();
                out.println(jsonStr);
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (null != out)
                {
                    out.close();
                }
            }
        }

        try
        {

            JSONObject json = JSONObject.fromObject(result);
            String jsonStr = json.toString();
            if(!StringUtil.isNullOrEmptyStr(callback))
            {
                jsonStr =  callback + "("+ jsonStr +")";
            }


            out = response.getWriter();
            out.print(jsonStr);
        }
        catch (Exception e)
        {
        }
        finally
        {
            if (null != out)
            {
                out.close();
            }
        }
    }



}
